﻿using System.Windows;
using CodeIn.Diagnostics;
using CodeIn.Modules;
using CodeIn.Ui;
using System;
using CodeIn.Core;

namespace CodeIn {
	public partial class App : Application {
		public static string StartupLog { get; private set; }

		protected override void OnStartup(StartupEventArgs args) {
			base.OnStartup(args);
			MessageHandlers.Trace.MessageWritten += (s, e) => { System.Diagnostics.Trace.Write(e.Message); };
			MessageHandlers.Debug.MessageWritten += (s, e) => { System.Diagnostics.Debug.Write(e.Message); };
			MessageHandlers.Trace.MessageWritten += AddTraceToStartupLog;
			MessageHandlers.Debug.MessageWritten += AddTraceToStartupLog;

			var LocalTrace = MessageHandlers.Trace;
			var LocalDebug = MessageHandlers.Debug;

			// Load modules and Initialize them (as well as options)
			LocalDebug.OpenSection("Initialization");
			ModuleManager.Instance.LoadModules();
			ModuleManager.Instance.InitiliazeModules();
			OptionManager.Instance.Load();
			LocalDebug.WriteSeparator();
			ModuleManager.Instance.LoadStartupSequence();
			LocalDebug.CloseSection();

			// Handle args
			for (int i=0; i<args.Args.Length; i++) {
				if (args.Args[i] == "-reset") {
					foreach (var opt in OptionManager.Instance.RegisteredOptions)
						opt.Value.Reset();
				}
			}

			// Display welcome message
			LocalTrace.WriteSeparator();
			LocalTrace.WriteLine("----- CodeIn Project");
			LocalTrace.WriteLine("----- Made by Aurélien Ribon");
			LocalTrace.WriteLine("----- © 2010");
			LocalTrace.WriteSeparator();
			LocalTrace.WriteLine("All done, welcome !");

			// Create window
			MainWindowView view = new MainWindowView();
			view.Width = 1400;
			view.Height = 1000;
			var vm = new MainWindowViewModel();
			this.MainWindow = view;
			this.MainWindow.DataContext = vm;
			this.MainWindow.ContentRendered += (s, e) => {
				vm.IsInitializing = false;
			};

			AdjustWindowSize();
			this.MainWindow.Show();

			// Clean
			MessageHandlers.Trace.MessageWritten -= AddTraceToStartupLog;
			MessageHandlers.Debug.MessageWritten -= AddTraceToStartupLog;
		}

		protected override void OnExit(ExitEventArgs e) {
			base.OnExit(e);
			OptionManager.Instance.Save();
		}

		private void AddTraceToStartupLog(object sender, AsyncStaticMessageHandler.MessageWrittenEventArgs e) {
			StartupLog += e.Message;
		}

		private void AdjustWindowSize() {
			double maxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
			double maxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
			if (MainWindow.Width > maxWidth)
				MainWindow.Width = maxWidth - 20;
			if (MainWindow.Height > maxHeight)
				MainWindow.Height = maxHeight - 20;
		}
	}
}
